<template>
  <div class="product-detail-container">
    <a-row>
      <a-col :span="8">
        <div class="product-images">
          <div class="main-image-container">
            <button class="prev-button" @click="prevImage" v-if="currentImageIndex > 0">
              <LeftOutlined />
            </button>
            <img :src="currentImage" :alt="product.name" class="main-image" />
            <button class="next-button" @click="nextImage" v-if="product?.detail_images && currentImageIndex < product.detail_images.length - 1">
              <RightOutlined />
            </button>
          </div>
          <div class="thumbnail-container">
            <button class="prev-thumbnail-button" @click="prevThumbnail" v-if="thumbnailStartIndex > 0">
              <LeftOutlined />
            </button>
            <div class="thumbnail-list" ref="thumbnailList">
              <img
                v-for="(image, index) in visibleThumbnails"
                :key="index"
                :src="image"
                :alt="product.name"
                class="thumbnail"
                :class="{ 'active-thumbnail': currentImageIndex === index }"
                @click="selectImage(index)"
              />
            </div>
            <button class="next-thumbnail-button" @click="nextThumbnail" v-if="product?.detail_images && thumbnailStartIndex + visibleThumbnailsCount < product.detail_images.length">
              <RightOutlined />
            </button>
          </div>
        </div>
      </a-col>
      <a-col :span="16">
        <div class="product-info">
          <h2 class="product-title">{{ product.name }}</h2>
          <div class="product-price">{{ currencyType }} {{ proxy.$ConvertPrice(product.min_price) }}</div>
          <div class="product-specs">
            <h3>Product specifications</h3>
            <ul>
              <li v-for="(spec, index) in product.spec_list" :key="index">
                <div class="color-name">{{ spec.name.toUpperCase() }}： 
                  <span v-if="spec.name == 'size'" style="text-decoration: underline;cursor: pointer;">
                    <BarcodeOutlined style="margin-right: 4px;font-size: 12px;"/>Size Guide
                  </span>
                </div>
                <div class="go-flex" >
                    <div v-for="(val, index2) in spec.value" :key="index2">
                      <div v-if="spec.name == 'Color'" class="spec-image-container">
                        <img class="img" :src="val.name" :class="{'sizeActive': colorActive == val.name}" @click="colorClick(val.name)"/>
                      </div>
                      <div v-if="spec.name == 'size'" class="spec-size-container">
                        <div class="size-text" :class="{'sizeActive': sizeActive == val.name}" @click="sizeClick(val.name)"> {{ val.name }} </div>
                      </div>
                    </div>
                </div>
              </li>
            </ul>
          </div>
          <div class="product-description">
            <h3>Description</h3>
            <p>{{ product.description }}</p>
          </div>
          <div class="quantity-input">
            <button @click="decrement" class="quantity-button btn-minus">-</button>
            <input
              type="input"
              v-model="quantity"
              @input="updateQuantity"
              class="quantity-input-field"
              min="0"
            />
            <button @click="increment" class="quantity-button btn-plus">+</button>
          </div>

          <div class="product-actions">
            <button class="buy-button" @click="buyFn(product)">BUY NOW</button>
            <button class="favorite-button" @click="collectFn(product)">
              <HeartOutlined class="go-icon" style="font-size: 26x; color: #232323; cursor: pointer" />
            </button>
          </div>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch, getCurrentInstance } from 'vue';
import { LeftOutlined, RightOutlined, HeartOutlined, BarcodeOutlined } from '@ant-design/icons-vue';
import { useCurrencyStore } from '@/store'
const useCurrency = useCurrencyStore()
const { proxy } = getCurrentInstance()
interface SpecValue {
  name: string;
}

interface Spec {
  name: string;
  value: SpecValue[];
}

interface Product {
  name: string;
  max_price: number;
  description: string;
  spec_list: Spec[];
  detail_images: string[];
}

const props = defineProps({
  product: {
    type: Object as () => Product,
    required: true,
    default: () => ({
      name: '',
      max_price: 0,
      description: '',
      spec_list: [],
      detail_images: []
    })
  },
  modelValue: {
    type: Number,
    default: 1,
  },
  min: {
    type: Number,
    default: 1,
  },
  max: {
    type: Number,
    default: Infinity,
  },
});

const emit = defineEmits(['buy', 'collect', 'update:modelValue']);

// 货币
const currencyType = ref(useCurrency.currentCurrency.unit);
const currentImageIndex = ref(0);
const thumbnailStartIndex = ref(0);
const visibleThumbnailsCount = 5; // 每次显示的小图数量

const currentImage = computed(() => {
  if (!props.product?.detail_images || props.product.detail_images.length === 0) return ''
  return props.product.detail_images[currentImageIndex.value]
});
const visibleThumbnails = computed(() => {
  if (!props.product?.detail_images || props.product.detail_images.length === 0) return []
  return props.product.detail_images.slice(thumbnailStartIndex.value, thumbnailStartIndex.value + visibleThumbnailsCount);
});

const thumbnailList = ref<HTMLElement | null>(null);

const quantity = ref(props.modelValue);

watch(
  () => props.modelValue,
  (newValue) => {
    quantity.value = newValue;
  }
);

watch(
  () => quantity.value,
  (newValue) => {
    if(typeof !newValue === 'number'){
      quantity.value = 1;
    }
  }
);
let sizeActive = ref('');
const sizeClick = (size: string) => {
  sizeActive.value = size;
}

let colorActive = ref('');
const colorClick = (size: string) => {
  colorActive.value = size;
}

const increment = () => {
  if (quantity.value < props.max) {
    quantity.value++;
    emit('update:modelValue', quantity.value);
  }
};

const decrement = () => {
  if (quantity.value > props.min) {
    quantity.value--;
    emit('update:modelValue', quantity.value);
  }
};

const updateQuantity = (event: Event) => {
  const target = event.target as HTMLInputElement;
  let newQuantity = parseInt(target.value, 10);

  if (isNaN(newQuantity)) {
    newQuantity = props.min;
  } else {
    newQuantity = Math.max(props.min, Math.min(newQuantity, props.max));
  }

  quantity.value = newQuantity;
  emit('update:modelValue', newQuantity);
};

const prevImage = () => {
  if (currentImageIndex.value > 0) {
    currentImageIndex.value--;
  }
};

const nextImage = () => {
  if (currentImageIndex.value < props.product.detail_images.length - 1) {
    currentImageIndex.value++;
  }
};

const prevThumbnail = () => {
  if (thumbnailStartIndex.value > 0) {
    thumbnailStartIndex.value--;
  }
};

const nextThumbnail = () => {
  if (thumbnailStartIndex.value + visibleThumbnailsCount < props.product.detail_images.length) {
    thumbnailStartIndex.value++;
  }
};

const selectImage = (index: number) => {
  currentImageIndex.value = index;
};

const buyFn = (product: Product) => {
  console.log(`buy ${product}`);
  emit('buy', product);
};

const collectFn = (product: Product) => {
  console.log(`collect ${product}`);
  emit('collect', product);
};

onMounted(() => {
  if (thumbnailList.value) {
    thumbnailList.value.scrollLeft = 0;
  }
});
</script>

<style lang="scss" scoped>
.product-detail-container {
  /* display: flex; */
  justify-content: space-between;
  margin: 20px;
  
}

.product-images {
  /* width: 50%; */
  display: flex;
  flex-direction: column;
  align-items: center;
}

.main-image-container {
  position: relative;
  width: 100%;
  height: 500px;
  overflow: hidden;
}

.main-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.prev-button, .next-button {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  border-radius: 50%;
  padding: 10px;
  cursor: pointer;
  z-index: 10;
}

.prev-button {
  left: 10px;
}

.next-button {
  right: 10px;
}

.thumbnail-container {
  display: flex;
  align-items: center;
  margin-top: 10px;
  width: 100%;
  overflow: hidden;
}

.prev-thumbnail-button, .next-thumbnail-button {
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  border-radius: 50%;
  padding: 10px;
  cursor: pointer;
}

.thumbnail-list {
  display: flex;
  overflow-x: auto;
  scroll-behavior: smooth;
  gap: 10px;
  width: calc(100% - 60px); /* 减去两个按钮的宽度 */
}

.thumbnail {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border: 2px solid transparent;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.thumbnail:hover, .active-thumbnail {
  border-color: #007bff;
}

.product-info {
  /* width: 45%; */
  padding: 20px;
  /* background-color: #f9f9f9; */
  border-radius: 8px;
  padding-left: 50px;
  /* box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); */
}

.product-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}

.product-price {
  font-size: 20px;
  color: #f56c6c;
  margin-bottom: 20px;
}

.product-description {
  margin-bottom: 20px;
}

.product-description h3 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.product-description p {
  font-size: 14px;
  line-height: 1.6;
}

.product-specs {
  margin-bottom: 20px;
}

.product-specs h3 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.product-specs ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.product-specs li {
  font-size: 14px;
  margin-bottom: 5px;
}

.product-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.buy-button {
  padding: 10px 20px;
  background-color: #232323;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s ease;
  width: 40%;
}

.color-name{
  // font-weight: bold;
  margin-bottom: 6px;
}

.buy-button:hover {
  background-color: #ffffff;
  color: #232323;
}

.favorite-button {
  // padding: 15px 15px;
  width: 50px;
  height: 50px;
  background-color: #ffffff;
  color: white;
  border: 1px solid #c7c7c7;
  border-radius: 50%;
  cursor: pointer;
  transition: background-color 0.3s ease;
  .go-icon{
    transform: translateY(2px);
  }
}

.favorite-button:hover {
  background-color: #232323;
  .go-icon{
    color: #ffffff!important;
  }
}

.spec-image-container{
  border-radius: 50%;
  width: 60px; 
  height: 60px; 
  margin-right: 20px;
  >.img{
    width: 100%; 
    height: 100%; 
    object-fit: cover;
    border-radius: 50%;
  }
}
.spec-size-container, .spec-image-container{
  margin-bottom: 10px;
}

.quantity-input {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.quantity-button {
  padding: 9px 14px;
  border: 1px solid #ccc;
  background-color: #f9f9f9;
  cursor: pointer;
  transition: background-color 0.3s;
}

.quantity-button:hover {
  background-color: #e0e0e0;
}

.btn-minus{
  border-right: none;
}

.btn-plus{
  border-left: none;
}

.quantity-input-field {
  width: 50px;
  text-align: center;
  border: 1px solid #ccc;
  // margin: 0 5px;
  padding: 9px 5px;
  border-left: none;
  border-right: none;
  cursor: pointer;
  &:focus{
    outline: none;
  }
}

.size-text{
  font-size: 13px;
  font-family: Gotham !important;
  padding: 8px 8px;
  height: 34px;
  line-height: 34px;
  text-align: center;
  text-transform: capitalize;
  border: 1px solid #ccc;
  display: inline;
  cursor: pointer;
  margin-right: 10px;
}
.sizeActive{
  border: 2px solid #000;
}
</style>